// pages/collection/sheetdt/sheetdt.js
const db = wx.cloud.database()
Page({
  data: {
    flag: '',
    sheetKey: '',
    showInputDialog: false,
    showValueDialog: false,
    selectKey: '',
    selectValue: '',
    inputVlaue: '',
    sheetData: {}
  },
  onLoad: function (options) {
    console.log(options)
    if (!options.sheetKey) return
    var sheetKey = options.sheetKey
    var flag = options.flag
    var titleStr = sheetKey + "表详情"
    if (flag == "add") {
      titleStr = "添加" + sheetKey + "表"
    }
    wx.setNavigationBarTitle({
      title: titleStr
    })
    var sheetStr = decodeURIComponent(options.sheetStr)
    var sheetData = JSON.parse(sheetStr)
    // var sheetData = this.data.sheetData //测试使用
    console.log(sheetData)
    this.setData({
      sheetKey: sheetKey,
      flag: flag
    })
    this.initAddData(sheetData)
    this.convertSheetData(sheetData)
  },
  //初始化删除数据
  getDeleteParams(e, deleteFlag) {
    var deleteData = {}
    var deleteKey = ''
    const _db = db.command
    var keyStr = e.currentTarget.dataset.key
    var value = e.currentTarget.dataset.value
    console.log("key", keyStr, "value", value)
    //本地源数据
    var sheetKey = this.data.sheetKey
    var sheetData = this.data.sheetData
    //删除本地key值数据 及 初始化要删除的数据库数据
    switch (deleteFlag) {
      case "onKeyDeleteClick":
        console.log("getDeleteParams-onKeyDeleteClick")
        delete sheetData[keyStr]
        deleteData[keyStr] = _db.remove()
        deleteKey = keyStr
        break;
      case "onObjectKeyDeleteClick":
        var key = keyStr.split(",");
        console.log("getDeleteParams-onObjectKeyDeleteClick", key)
        delete sheetData[key[0]][key[1]]
        deleteData[key[0]] = {}
        deleteData[key[0]][key[1]] = _db.remove()
        deleteKey = key[0] + "-" + key[1]
        break;
      case "onStrListDeleteClick":
        var key = keyStr.split(",");
        console.log("getDeleteParams-onStrListDeleteClick", key)
        for (var i = 0; i < sheetData[key[0]].length; i++) {
          if (i == key[1]) {
            sheetData[key[0]].splice(i, 1)
            console.log("删除成功")
          }
        }
        console.log("sheetData", sheetData)
        deleteData[key[0]] = _db.pull(value)
        deleteKey = key[0] + "-" + value
        break
    }
    console.log("sheetData", sheetData)
    var deleteParams = {
      sheetKey: sheetKey,
      sheetData: sheetData,
      deleteKey: deleteKey,
      deleteData: deleteData
    }
    return deleteParams;
  },
  //初始化添加数据
  initAddData(objData) {
    var flag = this.data.flag
    if (flag != "add")
      return
    // console.log("initAddData-------------------")
    delete objData._id
    delete objData._openid
    for (var key in objData) {
      // console.log("initAddData-------------------", key)
      objData[key] = ""
    }
  },
  //转换数据为可识别数据
  convertSheetData(objData) {
    var sheetDetail = []
    for (let [key, value] of Object.entries(objData)) {
      // console.log(key + ':' + value);
      if (value instanceof Array) {
        console.log("Array", value);
        var mapData = {}
        var array0 = value[0]
        if (array0 instanceof Object) { //objList
          mapData = {
            key: key,
            objList: value
          }
        } else { //strList
          mapData = {
            key: key,
            strList: value
          }
        }
        sheetDetail.push(mapData)
      } else if (value instanceof Object) {
        console.log("Object", value);
        var mapData = {
          key: key,
          object: value
        }
        sheetDetail.push(mapData)
      } else {
        console.log("Other", value);
        var mapData = {
          key: key,
          value: value + ""
        }
        sheetDetail.push(mapData)
      }
    }
    this.setData({
      sheetData: objData,
      sheet: sheetDetail
    })
  },
  //删除数据逻辑
  deleteKeyProcess(e, deleteTag) {
    var params = this.getDeleteParams(e, deleteTag)
    this.convertSheetData(params.sheetData)
    this._updateDataInDB(params.sheetKey, params.sheetData, params.deleteData, params.deleteKey)
  },
  //key删除点击监听
  onKeyDeleteClick(e) {
    // console.log("onKeyDeleteClick", e)
    this.deleteKeyProcess(e, "onKeyDeleteClick")
  },
  //object对象里面的key值删除
  onObjectKeyDeleteClick(e) {
    console.log("onObjectKeyDeleteClick", e)
    this.deleteKeyProcess(e, "onObjectKeyDeleteClick")
  },
  //str列表删除点击监听
  onStrListDeleteClick(e) {
    console.log("onStrListDeleteClick", e)
    this.deleteKeyProcess(e, "onStrListDeleteClick")
  },
  //删除数据库key值数据
  _updateDataInDB(sheetKey, sheetData, deleteData, deleteKey) {
    console.log("_updateDataInDB", sheetKey, sheetData._id, deleteData, deleteKey)
    db.collection(sheetKey).doc(sheetData._id).update({
      data: deleteData,
      success: res => {
        console.log("数据库操作结果成功", deleteData, res)
        wx.showToast({
          icon: "none",
          title: '更新' + deleteKey + "字段成功!"
        })
      },
      fail: err => {
        console.error("数据库操作结果失败", err)
      }
    })
  },
  //value值点击监听
  onValueClick(e) {
    console.log("onValueClick")
    this._showInputDialog(e, "onValueClick")
  },
  //string数组中的value点击监听
  onStrListValueClick(e) {
    console.log("onStrListValueClick")
    this._showInputDialog(e, "onStrListValueClick")
  },
  //string数组中的添加按钮监听
  onStrListAddClick(e) {
    console.log("onStrListAddClick")
    this._showInputDialog(e, "onStrListAddClick")
  },
  //显示弹窗
  _showInputDialog(e, updateTag) {
    var key = e.currentTarget.dataset.key
    var value = e.currentTarget.dataset.value
    console.log("key", key, "value", value)
    this.setData({
      showInputDialog: true,
      selectKey: key,
      selectValue: value,
      updateTag: updateTag
    })
  },
  //弹窗输入监听
  _inputListener: function (e) {
    console.log("inputListener--", e.detail)
    this.setData({
      inputVlaue: e.detail.value
    })
  },
  //弹窗按钮点击监听
  _btnClick: function (e) {
    console.log("btnClick--", e)
    var btnClick = e.detail
    if (btnClick.value == "确定") {
      this._updateValueProcess()
    }
    this.setData({
      showInputDialog: false
    })
  },
  //删除数据逻辑
  _updateValueProcess() {
    var flag = this.data.flag
    var params = this._getUpdateParams()
    this.convertSheetData(params.sheetData)
    if (flag == "add") {
      //做添加逻辑
    } else {
      this._updateDataInDB(params.sheetKey, params.sheetData, params.upateData, params.updateKey)
    }
  },
  //获取更新参数
  _getUpdateParams() {
    var upateData = {}
    var updateKey = ''
    const _db = db.command
    //本地源数据
    var sheetKey = this.data.sheetKey
    var sheetData = this.data.sheetData
    var keyStr = this.data.selectKey
    var value = this.data.selectValue
    var inputVlaue = this.data.inputVlaue
    //操作标识
    var flag = this.data.flag
    var updateFlag = this.data.updateTag
    console.log("inputVlaue", inputVlaue)
    var resValue
    if (inputVlaue == "true" || inputVlaue == "false") {
      resValue = inputVlaue == "true" ? true : false
    } else {
      resValue = inputVlaue
    }
    //删除本地key值数据 及 初始化要删除的数据库数据
    switch (updateFlag) {
      case "onValueClick":
        sheetData[keyStr] = resValue
        console.log("_getUpdateParams-onValueClick")
        upateData[keyStr] = resValue
        updateKey = keyStr
        break;
      case "onStrListAddClick":
        var key = keyStr.split(",");
        // console.log("key[1]==============", key[1], typeof(key[1]))
        sheetData[key[0]].splice(key[1] + 1, 0, inputVlaue)
        upateData[key[0]] = _db.push({
          each: [inputVlaue],
          position: parseInt(key[1]) + 1,
        })
        updateKey = "key[0]=" + key[0] + "-" + "key[1]=" + key[1] + inputVlaue
        break;
      case "onStrListValueClick":
        var key = keyStr.split(",");
        console.log("_getUpdateParams-onStrListValueClick", key)
        var index = 0
        for (var i = 0; i < sheetData[key[0]].length; i++) {
          if (i == key[1]) {
            index = i
            sheetData[key[0]][i] = inputVlaue
            console.log("修改成功")
          }
        }
        console.log("sheetData", sheetData)
        upateData[key[0]] = _db.push({
          each: [inputVlaue],
          position: index,
        })
        updateKey = "key[0]=" + key[0] + "-" + "key[1]=" + key[1] + inputVlaue
        break
    }
    console.log("sheetData", sheetData)
    var updateParams = {
      sheetKey: sheetKey,
      sheetData: sheetData,
      updateKey: updateKey,
      upateData: upateData
    }
    return updateParams;
  },
  //添加数据表
  addSheetClick(e) {
    var sheetKey = this.data.sheetKey
    var sheetData = this.data.sheetData
    db.collection(sheetKey).add({
      data: sheetData,
      success: res => {
        console.log("数据库操作结果成功", sheetData, res)
        wx.showToast({
          icon: "none",
          title: '添加数据表成功!'
        })
      },
      fail: err => {
        console.error("数据库操作结果失败", err)
      }
    })
  },
  //选择value弹窗
  onSelectValueAtt(e) {
    var key = e.currentTarget.dataset.key
    console.log(e)
    this.setData({
      selectKey: key,
      showValueDialog: true
    })
  },
  //选择value弹窗
  radioValueCheck(e) {
    // console.log("radioCheck--", e)
    var valueRadio = e.detail
    var selectKey = this.data.selectKey
    var sheetData = this.data.sheetData
    console.log("radioCheck--", valueRadio, selectKey, sheetData)
    switch (valueRadio.value) {
      case "String":
        sheetData[selectKey] = " "
        break
      case "Boolean":
        sheetData[selectKey] = valueRadio.checked
        break
      case "Array":
        sheetData[selectKey] = [" "]
        break
      case "List":
        sheetData[selectKey] = []
        break
    }
    console.log("sheetData", sheetData)
    this.convertSheetData(sheetData)
    this.setData({
      showValueDialog: false
    })
  }
})